<?php
namespace Nearby\Controller;
use Common\Controller\CommonController;

/**
 * 附近的人模块
 */
class NearbyController extends CommonController {
	
	protected function _initialize(){
		parent::_initialize();
		$this->_mycache = S(C('REDIS_DSN'));
		$this->_auth();
		
		$this->_moduleid = 106;
		$this->_cust_location = new \Common\Model\CustLocationModel();
	}
    
    
    
	/**
	 * 查找附近的用户
	 */
	public function searchAction(){
		$longitude = I('request.longitude');
		$latitude = I('request.latitude');
		$sex = I('request.sex');
		$this->_search($longitude , $latitude , $sex);
	}
	
	private function _search($longitude , $latitude , $sex = null){
		if(empty($longitude) || empty($latitude)){
    		$this->status = 1000;
    		$this->msg = L('STATUS_1000');
    		$this->outPut();
		}
		
		$geohash = new \Geohash();
		$hash = $geohash->encode($latitude, $longitude);
		$this->_setLocation($latitude , $longitude , $hash);
		
		$custData = $custidsArr = array();
		$geoinStr = '';
		for($length = 6; $length >= 0; $length--) {
			if ($length > 0) {
				$geobox = $geohash->neighbors(substr($hash, 0, $length));
				$geobox[] = substr($hash, 0, $length);
				$geoinStr = "'" . implode("','", $geobox) . "'";
			} else {
				$geoinStr = '';
			}
		
			
			$result = $this->_cust_location->getGEOCust($geoinStr, $length, 50 - count($custData) , $sex);
			//dump($result);exit;
			if(empty($result)) continue;
			foreach ($result as &$geoCust) {
				if ($geoCust['custid'] == $this->_custInfo['custid'] || in_array($geoCust['custid'], $custidsArr)) {
					continue;
				}
				
				$custInfo = $this->_getCustInfo($geoCust['custid']);
				if (empty($custInfo)) {
					continue;
				}
				
				$cust = array();
				$cust['custid'] = $custInfo['custid'];
				$cust['nickname'] = $custInfo['nickname'];
				$cust['signature'] = $custInfo['signature'];
				$cust['sex'] = $custInfo['sex'];
				$cust['geodate'] = empty($geoCust['updatetime']) ? 0 : strtotime($geoCust['updatetime']);
				$cust['geodistance'] = '';
				if (intval($latitude) && intval($longitude) && !empty($geoCust['longitude']) && !empty($geoCust['latitude'])) {
					$distance = \tools::getDistance($latitude, $longitude, $geoCust['latitude'], $geoCust['longitude']);
					$cust['geodistance'] = \tools::getDistanceFormate($distance, $cust['geodate']);
					$cust['distance'] = $distance;
				} else {
					$cust['distance'] = PHP_INT_MAX;
				}
				$custData[$cust['custid']] = $cust;
				$custidsArr[] = $geoCust['custid'];
			}
		
			if (count($custData) >= 50) {
				break;
			}
		}
		
		usort($custData, "sortGEO");
		foreach ($custData as &$cust) {
			unset($cust['distance']);
			unset($cust['geodate']);
		}
		
		$this->data = $custData;
		$this->outPut();
		
	}
    
	
	
	/**
	 * 清除用户的经纬度
	 */
	public function clearLocationAction(){
		$this->_clearLocation();
	}
	
	private function _clearLocation(){
		$this->_delLocation($this->_custInfo['custid']);
	}
	
}
